package com.ww.learn.coroutine

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.actor

sealed class CounterMsg
object IncCounter : CounterMsg() // 递增计数器的单向消息
class GetCounter(val response: CompletableDeferred<Int>) : CounterMsg() // 携带回复的请求

fun CoroutineScope.counterActor() = actor<CounterMsg> {
    var counter = 0 // actor状态
    for (msg in channel) { // 即将到来消息的处理
        when (msg) {
            is IncCounter -> counter++
            is GetCounter -> msg.response.complete(counter)
        }
    }
}

class Test {
    suspend fun test() = withContext(Dispatchers.IO) {
        val counterActor = counterActor() // 创建该actor
        repeat(100) {
            launch {
                repeat(1000) {
                    counterActor.send(IncCounter)
                }
            }
        }
        launch {
            delay(3000)
            val response = CompletableDeferred<Int>()
            counterActor.send(GetCounter(response))
            println("Counter = ${response.await()}")
            counterActor.close() // 关闭该actor
        }
    }
}

suspend fun main() {
    Test().test()
}

suspend fun calA(): Int {
    printWithThreadInfo()
    delay(1000)
    return 1
}